/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DBConnect;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Hoang Quan
 */
public class DBConnect {
    public static String driver = "com.mysql.jdbc.Driver";
    public static String url = "jdbc:mysql://localhost:3306/";
    public static String dbName ="banhang";
    public static String user ="root";
    public static String pass = "";
    public static Connection cnn;
    
    public static boolean open() {
        try {
            //ket noi db o day

            if (cnn == null || cnn.isClosed()) {
                Class.forName(driver);
                String dbURL = "jdbc:mysql://localhost:3306/" + dbName + "?user=root&password=&useUnicode=true&characterEncoding=UTF-8";
                cnn = DriverManager.getConnection(dbURL);
            }
            return true;

        } catch (SQLException ex) {
            Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, ex);
        }

        return false;

    }

    public static void close() {
        try {
            if (cnn != null && !cnn.isClosed()) {

                cnn.close();

            }
        } catch (SQLException ex) {
            Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public static void close(PreparedStatement ps) {
        try {
            
            if (ps != null && !ps.isClosed()) {

                ps.close();

            }
        } catch (SQLException ex) {
            Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, ex);
        }
       close();
    }
    public static void close(PreparedStatement ps, ResultSet rs) {
        try {
            
            if (rs != null && !rs.isClosed()) {

                rs.close();

            }
        } catch (SQLException ex) {
            Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, ex);
        }
       
        close(ps);
    }
}
